package com.csg.web.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * 初始化器，channel注册后，执行初始化方法
 *
 * @author george
 */
public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        // 通过channel获取对应的pipeline
        ChannelPipeline pipeline = channel.pipeline();

        // 通过pipeline，添加handler
        // HttpServerCodec是由netty提供的助手类。
        // 当请求到服务端，需要解码，响应到客服端要编码
        pipeline.addLast("httpServerCodec", new HttpServerCodec());

        // 对写大数据流的支持
        pipeline.addLast("chunkedWriteHandler", new ChunkedWriteHandler());

        // 对httpMessage进行聚合，聚合成FullHttpRequest或者FullHttpResponse
        // 几乎在netty中的编程，都会使用
        pipeline.addLast("httpObjectAggregator", new HttpObjectAggregator(1024 * 60));

        // websocket服务器处理协议，用于指定给客户端连接访问的路由：/ws
        pipeline.addLast("webSocketServerProtocolHandler", new WebSocketServerProtocolHandler("/ws"));

        // 添加自定义的助手类
        pipeline.addLast("webSocketHandler", new WebSocketHandler());
    }
}
